# encoding=utf-8_general_ci

import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import torndb

from update import update

from config import *

class AdminHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return        

        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            self.render("error.html", user = user_info, error_message = "Incomplete Input", statu="danger")
            return

        user_info = db.get("select * from user where username='"+username+"'")

        status = db.query("select * from status")
        questions = db.query("select * from problems")
        users = db.query("select * from user")

        self.render("admin.html", user = user_info, status = status, users = users, questions = questions)

class AdminOperationHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_secure_cookie('user'):
            self.redirect("/login")
            return

        username = self.get_secure_cookie("user")

        try:
            db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
        except:
            self.render("error.html", user = user_info, error_message = "Incomplete Input", statu="danger")
            return

        user_info = db.get("select * from user where username='"+username+"'")

        if user_info.authority < 3:
            self.render("error.html", user = user_info, error_message = "Incomplete Input", statu="danger")
            return

        operation = self.get_argument("operation", "")
        runid = self.get_argument("runid", "")
        pid = self.get_argument("pid", "")
        statu = self.get_argument("statu", "")

        if operation == "rejudge":
            db.execute("update status set remark=0,statu='waiting' where runid='" + str(runid) + "'") 
            update()
        elif operation == "kill":
            db.execute("update status set statu='compulsory killed',remark=1 where runid='" + str(runid) + "'")
        elif operation == "validate":
            db.execute("update problems set valid=1 where pid="+str(pid))
        elif operation == "invalidate":
            db.execute("update problems set valid=0 where pid="+str(pid))

        self.redirect("/admin")

